package com.example.fruitshop;

import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class AddressActivity extends AppCompatActivity {
    private ListView listView;
    private boolean isAddressChecked = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);

        this.listView = findViewById(R.id.list_delivery_address);
        this.listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        Button button = findViewById(R.id.btn_ensure_address);
        TextView warn = findViewById(R.id.text_warn_not_choose_address);

        this.listView.setOnItemClickListener(((adapterView, view, position, id) -> {
            this.isAddressChecked = true;
            warn.setVisibility(View.INVISIBLE);
            CheckedTextView v = (CheckedTextView) view;
            boolean currentCheck = v.isChecked();
            Address address = (Address) listView.getItemAtPosition(position);
            address.setActive(!currentCheck);
        }));

        button.setOnClickListener(view -> submitSelectedAddress());
        this.initAddressData();
    }

    private void initAddressData() {
        Address gotham = new Address("Gotham City");
        Address central = new Address("Central City");
        Address star = new Address("Star City");
        Address metropolis = new Address("Metropolis");
        Address coast = new Address("Coast City");
        Address[] addresses = new Address[]{gotham, central, star, metropolis, coast};
        ArrayAdapter<Address> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice, addresses);
        this.listView.setAdapter(arrayAdapter);

        for (int i = 0; i < addresses.length; i++) {
            this.listView.setItemChecked(i, addresses[i].isActive());
        }
    }

    private void submitSelectedAddress() {
        TextView warn = findViewById(R.id.text_warn_not_choose_address);
        if (!this.isAddressChecked) {
            warn.setVisibility(View.VISIBLE);
            Vibrator mVibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            mVibrator.vibrate(300);
        } else {
            int pos = listView.getCheckedItemPosition();
            Address targetAddress = (Address) listView.getAdapter().getItem(pos);
            Intent intent = new Intent(AddressActivity.this, OrderActivity.class);
            intent.putExtra("address", targetAddress);
            startActivity(intent);
        }
    }
}
